package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TUser;
import com.bwie.service.TUserService;
import com.bwie.mapper.TUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 28463
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-06-17 09:29:41
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{
    @Autowired
    TUserMapper tUserMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        //校验用户姓名
        TUser tUser = tUserMapper.selectOne(new QueryWrapper<TUser>().lambda().eq(TUser::getUserName, loginInfoVo.getUserName()));
        //判断用户是否存在
        if(tUser==null){
            return R.ERROR(500,"用户不存在请先注册");
        }
        //获取token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tUser.getUserId()).claim("userName", tUser.getUserName()).compact();
        //获取token的键值
        String tokenKey="token-"+tUser.getUserId();
        //将token存入redis缓存
        stringRedisTemplate.opsForValue().set(tokenKey,token,30, TimeUnit.MINUTES);
        //根据用户id获取token;
        tUser.setToken(token);
        return R.OK(tUser);
    }

    @Override
    public R addUser(TUser tUser) {
        tUserMapper.insert(tUser);
        return R.OK();
    }

    @Override
    public R sendCode(String mobile) {
        String sendKey="mobile:"+mobile;
        Boolean hasKey = stringRedisTemplate.hasKey(sendKey);
        if(hasKey){
            return R.ERROR(500,"验证码发送频繁");
        }
        boolean mobile1 = Validator.isMobile(mobile);
        if(!mobile1){
            return R.ERROR(500,"手机号格式不正确");
        }
        TUser tUser = new TUser();
        if(mobile.equals(tUser.getMobile())){
            return R.ERROR(500,"手机号不能重复");
        }
        String code = RandomUtil.randomNumbers(4);
        MobileMessageUtil.sendMobileMessage(mobile,code);

        String mobileKey="mobile:"+mobile;
        stringRedisTemplate.opsForValue().set(mobileKey,code,5,TimeUnit.MINUTES);
        System.out.println("手机号验证码为:"+code);
        return R.OK(code);
    }
}




